home *** CD-ROM | disk | FTP | other *** search
- Path: Rezonet.net!news
- From: ray@ultimate-tech.com (Ray Dunn)
- Newsgroups: comp.lang.c
- Subject: Re: Recursive function -> how do you exit one?
- Date: 29 Jan 1996 01:26:06 GMT
- Organization: Ultimate Technographics Inc.
- Message-ID: <4eh7ne$166g@ns.RezoNet.NET>
- References: <4eh1g8$aba@pulp.ucs.ualberta.ca>
- NNTP-Posting-Host: 204.19.230.7
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.7
-
- In referenced article, Jacob Bukczynski says...
- >
- >I'm using a recursive function to search for files. I need
- >it to quit when a user presses Esc.
- >
- >Using
- >
- >return;
- >
- >doesn't seem to work, the funtion runs again. ( I tested
- >this by putting a printf statement in front of the return -
- >it got printed over and over again. )
-
- Each call of the function returns through its end or return call in the
- normal way. So that in:
-
- void f(int n)
- {
- printf("IN %d ", n);
-
- if (n < 2)
- f(n+1);
-
- printf("OUT %d ", n);
- return;
- }
-
- if f(0) is called, it would print
-
- IN 0 IN 1 IN 2 OUT 2 OUT 1 OUT 0
-
- - IN's when the function recurses in, then OUT's as all calls of the
- function return.
-
- If you want to do something special to unwind the calls, on an error or
- special user input say, then you either have to use a setjmp in the
- function which makes the first call of the recursive function, and use
- longjmp to get out, or, more normally, you must return an error code
- which you test after the recursive call, to ensure that the calls
- unwind immediately.
-
- int f(some_parameters)
- { int ret;
-
- some_processing...
-
- if (some_error_condition)
- return(-1);
-
- some_more_processing...
-
- ret = f(some_args); /* recursive call */
- if (ret == -1)
- return(-1); /* return immediately if error */
-
- some_other_processing...
-
- return(0);
- }
- --
- Ray Dunn (opinions are my own) | Phone: (514) 938 9050
- Montreal | Phax : (514) 938 5225
- ray@ultimate-tech.com | Home : (514) 630 3749
-
-